﻿using System;
using System.Threading;
using System.Collections.Generic;

namespace Net.System
{
    /// <summary>
    /// 线程池
    /// </summary>
    public class ThreadPool
    {
        private static readonly List<ThreadWorker> workers;
        private static int workerCount;

        static ThreadPool()
        {
            workers = new();
            var threadCount = Environment.ProcessorCount;
            SetThreadCount(threadCount);
        }

        public static void SetThreadCount(int threadCount)
        {
            for (int i = 0; i < workers.Count; i++)
                workers[i].Stop();
            workers.Clear();
            for (int i = 0; i < threadCount; i++)
            {
                var threadWorker = new ThreadWorker();
                threadWorker.Start($"ThreadPool-{i + 1}");
                workers.Add(threadWorker);
            }
        }

        public static void UnsafeQueueUserWorkItem(Action callback)
        {
            workers[workerCount++ % workers.Count].QueueWorker(callback);
        }

        public static void UnsafeQueueUserWorkItem(WaitCallback callback, object state)
        {
            workers[workerCount++ % workers.Count].QueueWorker(callback, state);
        }

        public static void UnsafeQueueUserWorkItem<T>(Action<T> callback, T state)
        {
            workers[workerCount++ % workers.Count].QueueWorker(callback, state);
        }
    }
}